<template>
  <ContentWrap>
    <!-- 搜索栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="80px"
    >
      <!-- 租户 -->
      <el-form-item label="租户" prop="rechargeTenantId">
        <el-select
          v-model="queryParams.rechargeTenantId"
          placeholder="请选择租户"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="opt in tenantOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="过滤网关" prop="filterName">
        <el-input
          v-model="queryParams.filterName"
          placeholder="请输入过滤网关"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="密钥" prop="appSecret">
        <el-input
          v-model="queryParams.appSecret"
          placeholder="请输入密钥"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item label="到期时间" prop="expireTime">
        <el-date-picker
          v-model="queryParams.expireTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>

      <!-- 产品权限（字典：REQUEST_TYPE）- 搜索：单选 -->
      <el-form-item label="产品权限" prop="productPermissions">
        <el-select
          v-model="queryParams.productPermissions"
          placeholder="请选择产品权限"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="opt in reqTypeOptions"
            :key="opt.value"
            :label="opt.label"
            :value="opt.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="启用状态" prop="enabled">
        <el-select
          v-model="queryParams.enabled"
          placeholder="请选择"
          clearable
          class="!w-240px"
        >
          <el-option :value="1" label="启用" />
          <el-option :value="0" label="停用" />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['vos:secret-account:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['vos:secret-account:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['vos:secret-account:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="租户" align="center" prop="rechargeTenantId" min-width="120">
        <template #default="{ row }">
          {{ tenantNameMap[row.rechargeTenantId] ?? row.rechargeTenantId ?? '-' }}
        </template>
      </el-table-column>

      <el-table-column label="过滤网关" align="center" prop="filterName" min-width="120" />

      <!-- 新增：随路数据（attach） -->
      <el-table-column
        label="随路数据"
        align="center"
        prop="attach"
        min-width="260"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          {{ formatAttach(row.attach) }}
        </template>
      </el-table-column>

      <!-- 不脱敏，直接显示密钥 -->
      <el-table-column label="密钥" align="center" prop="appSecret" min-width="220" />

      <!-- 产品权限展示（将逗号分隔的值映射为字典中文，用顿号连接） -->
      <el-table-column label="产品权限" align="center" prop="productPermissions" min-width="160">
        <template #default="{ row }">
          {{ formatProductPermissions(row.productPermissions) }}
        </template>
      </el-table-column>

      <el-table-column
        label="到期时间"
        align="center"
        prop="expireTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="余额(元)" align="center" prop="balance" width="110">
        <template #default="{ row }">
          {{ formatMoney(row.balance) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="enabled" width="100">
        <template #default="{ row }">
          <el-tag :type="row.enabled ? 'success' : 'info'">
            {{ row.enabled ? '启用' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" min-width="220" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['vos:secret-account:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="warning"
            @click="openRecharge('recharge', scope.row.id)"
            v-hasPermi="['vos:secret-account:recharge']"
          >
            充值
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['vos:secret-account:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SecretAccountForm ref="formRef" @success="getList" />
  <!-- 表单弹窗：充值 -->
  <SecretAccountRechargeForm ref="rechargeRef" @success="getList" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { SecretAccountApi, type SecretAccount } from '@/api/vos/secretaccount'
import * as TenantApi from '@/api/system/tenant'
import SecretAccountForm from './SecretAccountForm.vue'
import SecretAccountRechargeForm from './SecretAccountRechargeForm.vue'
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'

defineOptions({ name: 'SecretAccount' })

const message = useMessage()
const { t } = useI18n()

/** 字典：产品权限 */
const reqTypeOptions = getStrDictOptions(DICT_TYPE.REQUEST_TYPE)
const reqTypeMap: Record<string, string> = {}
reqTypeOptions.forEach((d: any) => (reqTypeMap[String(d.value)] = d.label))

/** 下拉：租户 */
type TenantOption = { value: number; label: string }
const tenantOptions = ref<TenantOption[]>([])
const tenantNameMap = reactive<Record<number, string>>({})
const loadTenants = async () => {
  const res = await TenantApi.getTenantList()
  const arr = Array.isArray(res) ? res : (res?.list ?? [])
  tenantOptions.value = arr.map((it: any) => {
    const id = Number(it.id)
    const label = it.name || `租户#${id}`
    tenantNameMap[id] = label
    return { value: id, label }
  })
}

/** 列表相关 */
const loading = ref(true)
type SA = SecretAccount & { attach?: any }
const list = ref<SA[]>([])
const total = ref(0)
const queryParams = reactive<any>({
  pageNo: 1,
  pageSize: 10,
  rechargeTenantId: undefined,
  filterName: undefined,
  appSecret: undefined,
  expireTime: [], // [start, end]
  productPermissions: undefined, // 搜索：单选一个产品权限
  enabled: undefined,
  createTime: [] // [start, end]
})
const queryFormRef = ref()
const exportLoading = ref(false)

/** 工具：金额格式化 */
const formatMoney = (v: any) => {
  if (v === null || v === undefined || v === '') return '0.00'
  const n = Number(v)
  if (Number.isNaN(n)) return String(v)
  return n.toFixed(2)
}

/** 工具：产品权限格式化展示 */
const formatProductPermissions = (val: any) => {
  if (!val) return '-'
  const codes = String(val).split(',').map((s) => s.trim()).filter(Boolean)
  if (!codes.length) return '-'
  const labels = codes.map((c) => reqTypeMap[c] ?? c)
  return labels.join('、')
}

/** 工具：attach 格式化（字符串原样显示；对象转 JSON；为空显示 '-'） */
const formatAttach = (v: any) => {
  if (v === null || v === undefined || v === '') return '-'
  if (typeof v === 'string') return v
  try {
    return JSON.stringify(v)
  } catch {
    return String(v)
  }
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SecretAccountApi.getSecretAccountPage(queryParams)
    list.value = data.list || []
    total.value = data.total || 0
  } finally {
    loading.value = false
  }
}

/** 搜索/重置 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
const resetQuery = () => {
  queryFormRef.value?.resetFields?.()
  queryParams.pageNo = 1
  getList()
}

/** 新增/编辑弹窗 */
const formRef = ref()
const openForm = (type: 'create' | 'update', id?: number) => {
  formRef.value.open(type, id)
}

/** 充值弹窗 */
const rechargeRef = ref()
const openRecharge = (type: string, id: number) => {
  rechargeRef.value.open(type, id)
}

/** 删除/批量删除 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await SecretAccountApi.deleteSecretAccount(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: SecretAccount[]) => {
  checkedIds.value = records.map((item) => item.id)
}
const handleDeleteBatch = async () => {
  try {
    await message.delConfirm()
    await SecretAccountApi.deleteSecretAccountList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

/** 导出 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await SecretAccountApi.exportSecretAccount(queryParams)
    download.excel(data, '密钥管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  await loadTenants()
  await getList()
})
</script>
